package com.changgou.controller;

import com.alibaba.fastjson.JSONObject;
import com.changgou.service.WeixinPayService;
import com.changgou.util.Result;
import com.changgou.util.StatusCode;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.print.DocFlavor;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: WeixinPayController
 * @Author: ZWJ
 * @Date: 2020-09-08 21:12
 * @Synopsis: Null
 **/
@RestController
@RequestMapping(value = "/weixin/pay")
public class WeixinPayController {
    //交换机名字
    @Value("${mq.pay.exchange.order}")
    private String exchange;
    //路由
    @Value("${mq.pay.routing.key}")
    private String key;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /***
     * 支付回调
     * @param request
     * @return
     */
    @RequestMapping(value = "/notify/url")
    public String notifyUrl(HttpServletRequest request) {
        InputStream inputStream;
        try {
            //读取支付信息(输入流)
            inputStream = request.getInputStream();
            //输出流
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }

            //将支付的回调数据转换成xml字符串
            String result = new String(outputStream.toByteArray(), "utf-8");
            //将回调的xml数据转成map
            Map<String, String> map = WXPayUtil.xmlToMap(result);

            //从接受的数据中获取attach附加参数（交换机名字，路由）发送消息给交换机
            String attach = map.get("attach");
            Map<String,String> attachMap = JSONObject.parseObject(attach, Map.class);
            rabbitTemplate.convertAndSend(attachMap.get("exchange"),attachMap.get("queue"), JSONObject.toJSONString(map));
            //关闭流
            outputStream.close();
            inputStream.close();

            //设置响应数据
            Map returnMap = new HashMap();
            returnMap.put("return_code", "SUCCESS");
            returnMap.put("return_msg", "OK");
            //将响应数据返回
            return WXPayUtil.mapToXml(returnMap);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /***
     * 创建二维码
     * @return
     */
    @RequestMapping(value = "/create/native")
    public Result createNative(@RequestParam Map<String, String> dataMap) {
        Map<String, String> resultMap = weixinPayService.createNative(dataMap);
        return new Result(true, StatusCode.OK, "创建二维码预付订单成功！", resultMap);
    }

    /***
     * 查询支付状态
     * @param outtradeno
     * @return
     */
    @GetMapping(value = "/status/query")
    public Result<Map<String, String>> queryStatus(String outtradeno) {
        Map<String, String> map = weixinPayService.queryPayStatus(outtradeno);
        return new Result(true, StatusCode.OK, "查询状态成功", map);
    }
}
